package com.moter.demo01.requirements.socket_threadpool;

import java.io.*;
import java.net.Socket;


/**
 * 分配线程来处理客户端的数据传输
 */
public class ClientThread implements Runnable{
    private Socket client = null;

    public ClientThread(Socket client){
        this.client = client;
    }

    @Override
    public void run() {
        System.out.println(client.getInetAddress()+":"+client.getPort()+"连接到服务端");
        try {
            //输入流
            InputStream ips = client.getInputStream();
            //输出流
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
            writer.write("欢迎使用moter服务\n");
            writer.flush();
            while (true){
                byte[] data = new byte[1024];
                int msg = ips.read(data);
                if(msg==-1){
                    writer.write("服务端：\t连接关闭");
                    client.close();
                    break;
                }else if(msg>0){
                    System.out.println("client:"+client.getInetAddress()+client.getPort()+":\t"+new String(data));
                }else {
                    break;
                }

                writer.write("发送"+new String(data)+"\n");
                writer.flush();
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

    }
}
